package com.bjpowernode.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class TwoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 放行登录相关 login js css html servlet

        // 父类接口
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 1.调用请求对象读取请求包中请求行中URI，了解用户访问的资源文件是谁
        String requestURI = request.getRequestURI();//【/网站名/资源文件名 /myWeb/login.html or /myWeb/login or 。。
        // 】

        //2.如果本次请求资源文件与登陆相关【LoginServlet】此时应该无条件放行
        if(requestURI.indexOf("login") != 1 || "/myWeb".equals(requestURI)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.如果本次请求访问的是其他资源文件，需要得到用户在服务端HttpSession


        HttpSession session = request.getSession(false);
        // 子类扩充父类功能
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (session == null){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //4.做拒绝请求
        request.getRequestDispatcher("/login-error.html").forward(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {

    }
}
